﻿#define PROXY_AUTH

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Net;
using OpenWealth.DataManager;
using System.Threading;

namespace OpenWealth.Interface4EXE
{
    static class Program
    {

        static Boolean runForrestRun = true;

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        //[STAThread]
        static void Main()
        {

           Thread t = new Thread(WriteData);          

           t.Start();  
                
            Console.ReadLine();

            runForrestRun = false;

        }

        static void WriteData()
        {
            Default d = new Default();

            try
            {
                while (runForrestRun)
                {
                    Console.Write("Fetching... ");

                    d.FetchQuote("LON%3AHSBA");

                    Console.WriteLine(d.Company + "; " + d.Last);

                    Thread.Sleep(1000 * 10);    //10 seconds
                }
            }
            catch (Exception ex)
            {
                runForrestRun = false;

                Console.WriteLine(ex.Message);
            }
        }
    }


    class Default
    {
        public string Company { get; set; }
        public string Exchange { get; set; }
        public double Last { get; set; }
        public double High { get; set; }
        public double Low { get; set; }

        public void FetchQuote(string symbol)
        {
            string url = "http://www.google.com/finance?q=" + symbol;

#if PROXY_AUTH

            System.Net.WebProxy proxy = new System.Net.WebProxy("msk00-tmg01.rencap.com");
            proxy.Credentials = new NetworkCredential("DZhurikhin@rencap.com", "Moskvach0987");

            XmlTextReader rdr = new XmlTextReader(url);
            XmlUrlResolver resolver = new XmlUrlResolver();
            resolver.Proxy = proxy;
            rdr.XmlResolver = resolver;

            XDocument doc = XDocument.Load(rdr);
#else
            XDocument doc = XDocument.Load(url);
#endif
            Company = GetData(doc, "company");
            Exchange = GetData(doc, "exchange");
            Last = Convert.ToDouble(GetData(doc, "last"));
            High = Convert.ToDouble(GetData(doc, "high"));
            Low = Convert.ToDouble(GetData(doc, "low"));
        }

        public string GetData(XDocument doc, string name)
        {
            return doc.Root.Element("finance").Element(name).Attribute("data").Value;
        }
    }
}